package com.hunttown.mes.common.utils;

import org.apache.commons.lang.StringUtils;
import org.junit.Test;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 非对称加密
 * created by hunttown on 2017/7/27
 */
public class SHA1Utils {
    /**
     * SHA1加密（1）
     *
     * @param inStr 要加密的字符串
     * @return 返回40位SHA1
     */
    public static String shaEncode(String inStr) {
        try {
            if (StringUtils.isBlank(inStr)) {
                return null;
            }
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(inStr.getBytes(StandardCharsets.UTF_8));

            byte messageDigest[] = digest.digest();
            StringBuffer hexString = new StringBuffer();

            // 字节数组转换为 十六进制数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * SHA1加密（2） - 两个结果一致
     *
     * @param inStr 要加密的字符串
     * @return 返回40位SHA1
     */
    public static String shaEncodeSignature(String inStr) {
        if (StringUtils.isBlank(inStr)) {
            return null;
        }

        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(inStr.getBytes(StandardCharsets.UTF_8));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }
}
